# -*- coding: utf8 -*-

import os
from django.utils import simplejson as json
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.api import memcache
from Crypto.Hash import MD5
from Crypto.Cipher import DES
import datetime
from org.andolphin.models import *
import base64

# 返回结果代码常量
# 0以上为正确处理代码
RESULT_SUCCESS= 0
RESULT_SUCCESS_MSG = u'success'
# -99以下为系统错误代码
RESULT_METHOD_NOT_ALLOWED = -999
RESULT_METHOD_NOT_ALLOWED_MSG = u'http method is not allowed'
RESULT_INPUT_ERROR = -99
RESULT_INPUT_ERROR_MSG = u'input error'
RESULT_AUTH_ERROR = -100
RESULT_AUTH_ERROR_MSG = u'auth token is invalid!'
# -1到-98为应用错误代码
RESULT_USER_DUPLICATE = -2
RESULT_USER_DUPLICATE_MSG = u'user is duplicate!'
RESULT_USER_NOT_EXISTS = -3
RESULT_USER_NOT_EXISTS_MSG = u'user doest not exist!'
RESULT_PASSWORD_ERROR = -4
RESULT_PASSWORD_ERROR_MSG = u'password error!'

# 加密常量
DES_KEY = "yJ4Pd2N3"

class Result:
    def __init__(self, code, msg, data):
        self.result_code = code
        self.result_msg = msg
        self.data = data
        
    def toJson(self):
        return json.dumps({
               'code':self.result_code, 
               'message':self.result_msg, 
               'data':self.data
               }, sort_keys=True, indent=4)

def render_to_response(response, template_name, context):
    if template_name[-4:] == '.xml':
        response.headers["Content-Type"] = "text/xml"
    else:
        response.headers["Content-Type"] = "text/html"

    from os.path import dirname
    path = os.path.join(dirname(dirname(dirname(__file__))), "templates", template_name)
    response.out.write(template.render(path, context))

def render_json(response, r):
    response.headers['Content-Type'] = 'text/plain'
    response.out.write(r.toJson())


class MainPage(webapp.RequestHandler):
    def get(self):
        render_to_response(self.response, "index.html", {'current_module':'index'})

def password_md5(pwd):
    if pwd:
        m = MD5.new()
        m.update(pwd)
        return m.hexdigest()
    else:
        return pwd
    
def encode_token(pwd, t):
    des = DES.new(DES_KEY, DES.MODE_ECB)
    plain = pwd + t.strftime('%Y%m%d%H%M%S') + '00'
    ciph = des.encrypt(plain)
    return base64.b64encode(ciph)

def decode_token(token):
    des=DES.new(DES_KEY, DES.MODE_ECB)
    ciph = base64.b64decode(token)
    plain = des.decrypt(ciph)
    pwd = plain[0:32]
    time = datetime.datetime.strptime(plain[32:46], '%Y%m%d%H%M%S') 
    return (pwd, time)

import inspect

def props(obj):
    pr = {}
    for name in dir(obj):
        value = getattr(obj, name)
        if not name.startswith('__') and not inspect.ismethod(value):
            pr[name] = value
    return pr

def cleaned_errors(errors):
    if hasattr(errors, "__dict__"):
        d = {}
        for k, v in errors.iteritems():
            if not k.startswith('__'):
                d[k] = v.as_text()
        return d
    else:
        return errors
    
def get_value(obj, key, default_value=None):
    if obj == None or key == None:
        return default_value

    if hasattr(obj, "__dict__"):
        try:
            return obj[key]
        except KeyError:
            return default_value
    else:
        try:
            return getattr(obj, key)
        except AttributeError:
            return default_value

from middleware import AuthMiddleware, RestfulMethodMiddleware